package com.example.barry.udpdemo.Util;

import android.util.Log;

import org.json.JSONObject;

import java.net.DatagramPacket;
import java.net.Inet4Address;
import java.net.InetAddress;
import java.net.MulticastSocket;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.Enumeration;

/**
 * Created by barry on 17-2-20.
 */

public class UDPSend {
    public   String multicastHost="224.0.0.255";
    public void send(MulticastSocket ms){
                DatagramPacket dataPacket = null;
                try {
                    ms.setTimeToLive(4);
                    JSONObject jsonObject = new JSONObject().put("IP",getIpAddressString())
                            .put("deviceID","234")
                            .put("shopfloorID","2345");
                    //将本机的IP（这里可以写动态获取的IP）地址放到数据包里，其实server端接收到数据包后也能获取到发包方的IP
                    byte[] data =jsonObject.toString().getBytes();
                    InetAddress address = InetAddress.getByName(multicastHost);
                    //这个地方可以输出判断该地址是不是广播类型的地址
                    System.out.println(address.isMulticastAddress());
                    dataPacket = new DatagramPacket(data, data.length, address,
                            40000);
                    ms.send(dataPacket);
                    Log.i("发送数据为",""+dataPacket);
                    //  ms.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
    }
    public static String getIpAddressString() {
        try {
            for (Enumeration<NetworkInterface> enNetI = NetworkInterface
                    .getNetworkInterfaces(); enNetI.hasMoreElements(); ) {
                NetworkInterface netI = enNetI.nextElement();
                for (Enumeration<InetAddress> enumIpAddr = netI
                        .getInetAddresses(); enumIpAddr.hasMoreElements(); ) {
                    InetAddress inetAddress = enumIpAddr.nextElement();
                    if (inetAddress instanceof Inet4Address && !inetAddress.isLoopbackAddress()) {
                        return inetAddress.getHostAddress();
                    }
                }
            }
        } catch (SocketException e) {
            e.printStackTrace();
        }
        return "";
    }
}
